package exercise2;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Vector;

public class Server extends Thread{
	private Vector<Socket> clients = new Vector<Socket>();
	private ServerSocket ss = null;

	@Override
	public void run() {
		startServer();
		while(true){
			listen();
		}
		
	}
	private void startServer() {
		try {
			ss = new ServerSocket(3103);
			System.out.println("Server listening at port: "+ss.getLocalPort());
		} catch (IOException e) {
			System.err.println("Server could not be initiated!!!");
			e.printStackTrace();
		}

	}

	private void listen() {
		Socket client = null;
		try {
			client = ss.accept();
		} catch (IOException e) {
			e.printStackTrace();
		}
		clients.add(client);
		ServerThread st = new ServerThread(client);
		new Thread(st).start();
		System.out.println("New Client accommodated. Actual number: "+clients.size());
	}

	private class ServerThread implements Runnable {
		private Socket socket = null;
		private ObjectInputStream is = null;
		private ObjectOutputStream os = null;
		private ToBeBubbled tmpList = null;

		ServerThread(Socket client) {
			this.socket = client;
		}

		private void listen() {
			try {
				is = new ObjectInputStream(socket.getInputStream());
				Object obj = is.readObject();
				if (obj instanceof ToBeBubbled) {
					tmpList = bubbleSort((ToBeBubbled) obj);
				} else {
					System.out.println("Nothing to be bubbled");
				}
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}

		}

		public ToBeBubbled bubbleSort(ToBeBubbled tbb) {
			int[] list = tbb.getList();
			for (int i = 0; i < list.length; i++) {
				for (int j = 0; j < list.length; j++) {
					if (list[j] > list[i]) {
						int tmp = list[j];
						list[j] = list[i];
						list[i] = tmp;
					}
				}
			}
			return new ToBeBubbled(list);
		}

		public void run() {
			listen();
			/***************
			 * /* bubblesort! *
			 ***************/
			try {
				os = new ObjectOutputStream(socket.getOutputStream());
				os.writeObject(tmpList);
				System.out.println("finnished, sending back the list");
			} catch (IOException e) {
				e.printStackTrace();
			}
			/************************************
			 * /* finished, so callback the client *
			 ************************************/
		}

	}

}
